#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

#define CPU 2

struct param {
    int *array;
    int start;
    int end;
};

void *sort(void *arg)
{
    struct param *param;
    param = (struct param *)arg;
    for (int i = param->start; i < param->end - 1; i++) {
        int k = i;
        for (int j = i + 1; j < param->end; j++) {
            if (param->array[j] < param->array[k])
                k = j;
        }
        if (k != i) {
            int t = param->array[k];
            param->array[k] = param->array[i];
            param->array[i] = t;
        }
    }
}


void parallel_sort(int *array, int size)
{
    pthread_t workers[CPU];
    struct param params[CPU];
    int i;
    for (i = 0; i < CPU; i++) {
        struct param *param;
        param = &params[i];
        param->array = array;
        param->start = i * (size / 2);
        param->end = (i + 1) * (size / 2);
        pthread_create(&workers[i], NULL, sort, param);
    }
    for (i = 0; i < CPU; i++)
        pthread_join(workers[i], NULL);
    i = 0;
    int j = size / 2;
    int *t = malloc(sizeof(int) * size);
    int k =0;
    while (i != size / 2 && j != size) {
        if (array[i] < array[j]) {
            t[k] = array[i];
            i++;
            k++;
        }
        else {
            t[k] = array[j];
            j++;
            k++;
        }
    }
    if (i != size / 2) {
        for (; i < size / 2; i++) {
            t[k] = array[i];
            k++;
        }
    }
    if (j != size) {
        for (; j < size; j++) {
            t[k] = array[j];
            k++;
        }
    }
    for (i = 0; i < size; i++)
        array[i] = t[i];
}

int main()
{
    int array[8] = {3, 1, 2, 4, 5, 6, 7, 0};
    parallel_sort(array, 8);
    int i;
    for (i = 0; i < 8; i++)
        printf("%d\n", array[i]);
    return 0;
}
